package cn.tedu.boot51.controller;

import cn.tedu.boot51.entity.User;
import cn.tedu.boot51.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody User user){
        User u = mapper.select(user.getUsername());
        if (u!=null){
            return 3;
        }
        if (user.getUsername()==null||user.getPassword()==null||user.getNick()==null){
            return 2;
        }
        mapper.insert(user);
        return 1;
    }

    // 在参数列表里面声明 session 即可得到当前客户端对应的 Session
    @RequestMapping("/login")
    public int login (@RequestBody User user, HttpSession session){
        User u = mapper.select(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                // 把当前登录的用户对象保存到会话对象中
                // user代表用户输入的信息: 包括用户名和密码
                // u代表从数据库中查询到的信息,包括: id,用户名和密码,昵称
                session.setAttribute("user",u);
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        User u = (User) session.getAttribute("user");
        return u;
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        // 把登陆成功时保存的 user 对象删除
        session.removeAttribute("user");
    }
}
